using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
using MaterialDesignThemes.Wpf;

namespace LocalDns.UI
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : System.Windows.Application
    {
        private const string UniqueAppId = "LocalDnsService.UI.Application"; // 应用程序唯一标识符
        private Mutex? _mutex;
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        private const uint SWP_SHOWWINDOW = 0x0040;

        [DllImport("user32.dll")]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr FindWindow(string? lpClassName, string lpWindowName);

        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            // 检查是否已有实例在运行
            bool createdNew;
            _mutex = new Mutex(true, UniqueAppId, out createdNew);

            if (!createdNew)
            {
                // 已有实例在运行，激活已有窗口并退出当前实例
                ActivateExistingInstance();
                this.Shutdown();
                return;
            }

            // 初始化Material Design主题
            base.OnStartup(e);
        }

        private void ActivateExistingInstance()
        {
            // 查找主窗口并激活
            IntPtr handle = FindWindow(null, "LocalDnsService UI"); // 窗口标题，需要与MainWindow的Title属性匹配
            if (handle != IntPtr.Zero)
            {
                ShowWindow(handle, 1); // SW_SHOWNORMAL = 1
                SetForegroundWindow(handle);
                SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW);
                SetWindowPos(handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW);
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
            }
            base.OnExit(e);
        }
    }
}